<?php
//修改历史
//修改时间：2018/1/29
//修改人：lizenan
//修改功能：【后台管理】VIP服务数据导出异常
//任务ID：487
//
//修改时间：2018/2/2
//修改人：lizenan
//【后台管理】VIP数据导出，需求时间字段，只需日期信息
//任务ID：498
namespace backend\controllers;

use Yii;
use common\helps\tools;
use backend\models\SysSeq;
use yii\web\AdminController;
use backend\models\SysConfig;
use backend\models\ServiceVip;
//del by allen.qiang 20180127 删除无用代码 start
//use backend\models\SysCity;
//del by allen.qiang 20180127 删除无用代码 start
use backend\models\UploadForm;
use backend\models\ServiceVipLog;

class ServiceVipController extends AdminController
{
    public $layout = false;
    //业务关键字
    public $service = 'ServiceVip';
    //vip服务列表页
    public function actionIndex(){
        $model = new UploadForm();
        $sys_config = SysConfig::find()->where('config_group_name="vip服务"')->asArray()->all();
        //add by allen.qiang 20180127 459 【后台管理】后台管理操作日志优化化 start
        //操作日志
        $this->saveLog($this->service,'查询','VIEW','');
        //add by allen.qiang 20180127 459 【后台管理】后台管理操作日志优化     end
        return $this->render('index',['model'=>$model,'sys_config'=>$sys_config]);
//         $service_type = SysConfig::find()->select('config_key,config_value,config_title')->where('config_group_name="vip服务"')->asArray()->all();
//         $filename = dirname(dirname(__FILE__)).'/config/sys_city.php';
//         $sys_city = file_get_contents($filename);
//         $sys_city = json_decode($sys_city,1);
//         return $this->render('add',['service_type'=>$service_type,'sys_city'=>$sys_city]);
    }
    
    public function actionGetServiceVip(){
        $data = Yii::$app->request->post();
        //mod by lizenan 20180129 487 【后台管理】VIP服务数据导出异常 start
        //$query = ServiceVip::find()->select('create_time,service_type,home_time,cust_name,cust_tel,service_demand,status,id');
        $query = ServiceVip::find()->select('create_time,service_type,home_time,cust_name,cust_tel,service_demand,status,id,party_memo');
        //mod by lizenan 20180129 487 【后台管理】VIP服务数据导出异常 end
        if ($data['service_type']){
            $query = $query->where('service_type=:service_type',[':service_type'=>$data['service_type']]);
        }
        if ($data['status'] || $data['status'] === '0'){
            $query = $query->andWhere('status=:status',[':status'=>$data['status']]);
        }
        if (tools::arrayHasValue($data,'is_export')){
            $service_vip = $query->asArray()->all();
//             if (count($service_vip) == 0){
//                 $this->retJson('未查到可导出数据，请刷新页面重试',500);
//             }
            $service_vip_arr = [];
            $service_types = is_array($service_vip) && count($service_vip) > 0 ? array_filter(array_unique(array_column($service_vip, 'service_type'))) : '';
            if (count($service_types) > 0){
                $sys_config = SysConfig::find()->select('config_key,config_title')->where(['in','config_key',$service_types])->asArray()->all();
                $sys_config = array_combine(array_column($sys_config, 'config_key'), $sys_config);
                foreach ($service_vip as $serviceval){
                    $service_vip_arr[] = [
                        'create_time'=>$serviceval['create_time'],
                        'service_type_name'=>$sys_config[$serviceval['service_type']]['config_title'],
                        //mod by lizenan 20180202 【后台管理】VIP数据导出，需求时间字段，只需日期信息  498 start
                        //'home_time'=>$serviceval['home_time']
                        'home_time'=>$serviceval['home_time'] ? date('Y-m-d',strtotime($serviceval['home_time'])) : '',
                        //mod by lizenan 20180202 【后台管理】VIP数据导出，需求时间字段，只需日期信息  498 end
                        'cust_name'=>$serviceval['cust_name'],
                        'cust_tel'=>$serviceval['cust_tel'],
                        'party_memo'=>$serviceval['party_memo'],
                        'status'=>$serviceval['status'] == 1 ? '是' : '否',
                    ];
                }
            }
            $filed = ['create_time'=>'提交时间','service_type_name'=>'服务项目','home_time'=>'需求时间','cust_name'=>'姓名','cust_tel'=>'手机号','party_memo'=>'备注','status'=>'已处理'];
            $filename = 'service_vip_'.date('YmdHis').'.xls';
            $filename = iconv("utf-8", "gb2312", $filename);
            tools::exportExcel($filed, $service_vip_arr, $filename);
            //add by allen.qiang 20180127 459 【后台管理】后台管理操作日志优化化 start
            //操作日志
            $this->saveLog($this->service,'数据导出','EXPORT',\yii\helpers\Json::encode($service_vip_arr));
            //add by allen.qiang 20180127 459 【后台管理】后台管理操作日志优化     end
        }else{
            $count = $query->count();
            $sort_string = empty($data['columns'][$data['order'][0]['column']]['data']) ? 'id' : $data['columns'][$data['order'][0]['column']]['data'];
            $service_vip = $query->offset($data['start'])->limit($data['length'])->orderBy(
                [$sort_string=>$data['order'][0]['dir'] == 'asc' ? SORT_ASC : SORT_DESC])->asArray()->all();
                //查询出所有服务类型
            $list = array();
            $service_types = is_array($service_vip) && count($service_vip) > 0 ? array_filter(array_unique(array_column($service_vip, 'service_type'))) : '';
            if (count($service_types) > 0){
                $sys_config = SysConfig::find()->select('config_key,config_title')->where(['in','config_key',$service_types])->asArray()->all();
                $sys_config = array_combine(array_column($sys_config, 'config_key'), $sys_config);
                foreach ($service_vip as $serviceval){
                    $serviceval['home_time'] = $serviceval['home_time'] ? date('Y-m-d',strtotime($serviceval['home_time'])) : '';
                    $serviceval['service_type_name'] = tools::arrayHasValue($sys_config,$serviceval['service_type']) ? $sys_config[$serviceval['service_type']]['config_title'] : '';
                    $list[] = $serviceval;
                }
            }
            //$key = Yii::$app->params['sys_redis_prefix'].'service_vip_'.session_id();
            //Yii::$app->redis->setex($key,Yii::$app->params['frontend_session_timeout'],json_encode($list,JSON_UNESCAPED_UNICODE));
            $result['draw'] = intval($data['draw']);
            $result['recordsTotal'] = intval($count);
            $result['recordsFiltered'] = intval($count);
            $result['data'] = $list;
            return \yii\helpers\Json::encode($result);
        }
    }
    
    public function actionGetServiceVipDetail(){
        $data = Yii::$app->request->post();
        $service_vip = ServiceVip::find()->where('id=:id',[':id'=>$data['id']])->asArray()->one();
        $service_type = intval($service_vip['service_type']);
        $home_area = $service_vip['home_area'];
        $service_project = $service_vip['service_project'];
        $service_range = $service_vip['service_range'];
        $cust_style = $service_vip['cust_style'];
        $other = $service_vip['other'];
        $trip_partner = $service_vip['trip_partner'];
        $partner_count = $service_vip['partner_count'];
        $trip_preference = $service_vip['trip_preference'];
        $trip_budget = $service_vip['trip_budget'];
        $trip_day = $service_vip['trip_day'];
        if ($service_type){
            $sys_config = SysConfig::find()->select('config_title')->where('config_key='.$service_type)->asArray()->one();
            $service_vip['service_type_name'] = $sys_config['config_title'];
        }
        if ($home_area){
            $service_vip['home_area'] = $GLOBALS['_HOME_AREA_ARR'][$home_area];
        }
        if ($service_project){
            $service_project = json_decode($service_project);
            if ($service_type == 2){
                $service_type_name = '_CRM_SERVICE_PROJECT_BY';
            }elseif ($service_type == 4){
                $service_type_name = '_CRM_SERVICE_PROJECT_SC';
            }elseif ($service_type == 8){
                $service_type_name = '_CRM_SERVICE_PROJECT_PA';
            }
            $service_project_arr = [];
            if (is_array($service_project) && count($service_project) > 0)foreach ($service_project as $project){
                $service_project_arr[] = $GLOBALS[$service_type_name][$project];
            }
            $service_vip['service_project'] = implode('、', $service_project_arr);
        }
        if ($service_range){
            $service_range = json_decode($service_range);
            if ($service_type == 3){
                $service_range_name = '_SERVICE_RANGE_BY';
            }elseif ($service_type == 5){
                $service_range_name = '_SERVICE_RANGE_PH';
            }
            $service_range_arr = [];
            if (is_array($service_range) && count($service_range) > 0)foreach ($service_range as $range){
                $val = $GLOBALS[$service_range_name][$range];
                if ($val == '其他'){
                    $val = $other;
                }
                $service_range_arr[] = $val;
            }
            $service_vip['service_range'] = implode('、', $service_range_arr);
        }
        if ($cust_style){
            $cust_style = json_decode($cust_style);
            if ($service_type == 5){
                $service_range_name = '_CUST_STYLE_PH';
            }else{
                $service_range_name = '_CUST_STYLE_PA';
            }
            $cust_style_arr = [];
            if (is_array($cust_style) && count($cust_style) > 0)foreach ($cust_style as $style){
                $val = $GLOBALS[$service_range_name][$style];
                if ($val == '其他'){
                    $val = $other;
                }
                $cust_style_arr[] = $GLOBALS[$service_range_name][$style];
            }
            $service_vip['cust_style'] = implode('、', $cust_style_arr);
        }
        if ($trip_partner){
            $trip_partner = json_decode($trip_partner);
            $trip_partner_arr = [];
            if (is_array($trip_partner) && count($trip_partner) > 0)foreach ($trip_partner as $partner){
                $trip_partner_arr[] = $GLOBALS['_TRIP_PARTNER_DU'][$partner];
            }
            $service_vip['trip_partner'] = implode('、', $trip_partner_arr);
        }
        if ($partner_count){
            $service_vip['partner_count'] = $GLOBALS['_PARTNER_COUNT_DU'][$partner_count];
        }
        if ($trip_preference){
            $trip_preference = json_decode($trip_preference);
            $trip_preference_arr = [];
            if (is_array($trip_preference) && count($trip_preference) > 0)foreach ($trip_preference as $preference){
                $trip_preference_arr[] = $GLOBALS['_PARTNER_COUNT_DU'][$preference];
            }
            $service_vip['trip_preference'] = implode('、', $trip_preference_arr);
        }
        if ($trip_budget){
            $service_vip['trip_budget'] = $GLOBALS['_TRIP_BUDGET_DU'][$trip_budget];
        }
        if ($trip_day){
            $service_vip['trip_day'] = $GLOBALS['_TRIP_DAY_DU'][$trip_day];
        }
        $this->retJson($service_vip,200);
    }
    
    public function actionGetServiceVipLog(){
        $data = Yii::$app->request->post();
        $service_log = ServiceVipLog::find()->select('record,oper_time')->where('service_vip_id=:id',[':id'=>$data['id']])->asArray()->all();
        $this->retJson($service_log,200);
    }
    
    public function actionChangeServiceVipStatus(){
        $data_now = array();
        $model = new ServiceVip();
        $data = Yii::$app->request->post();
        $data_now['status'] = $data['status'];
        $data_now['editor'] = $model->getCreator();
        $data_now['edit_time'] = date('Y-m-d H:i:s',time());
        $where = ['id'=>$data['id']];
        $ret = $model::updateAll($data_now,$where);
        if(!$ret){
            throw new \Exception('操作失败');
        }
        //add by allen.qiang 20180127 459 【后台管理】后台管理操作日志优化化 start
        //操作日志
        $this->saveLog($this->service,'vip服务更新','MOD',\yii\helpers\Json::encode($data));
        //add by allen.qiang 20180127 459 【后台管理】后台管理操作日志优化     end
        $this->retJson('操作成功',200);
    }
    
    public function actionSaveVipServiceLog(){
        $data = Yii::$app->request->post();
        if (!$data['record']){
            $this->retJson('请填写联系记录',500);
        }
        $modal = new ServiceVipLog();
        $modal->service_vip_id = $data['service_vip_id'];
        $modal->record = $data['record'];
        $modal->operor = $modal->getCreator();
        $modal->oper_time = date('Y-m-d H:i:s');
        $modal->save();
        if (!$modal->attributes['id']){
            $this->retJson('联系记录保存失败',500);
        }
        //add by allen.qiang 20180127 459 【后台管理】后台管理操作日志优化化 start
        //操作日志
        $this->saveLog($this->service,'联系记录保存','ADD',\yii\helpers\Json::encode($data));
        //add by allen.qiang 20180127 459 【后台管理】后台管理操作日志优化     end
        $this->retJson('操作成功',200);
    }
    
    public function actionSaveServiceVip(){
        $data = Yii::$app->request->post();
        $service_key = $data['service_key'];
        $service_val = $data['service_val'];
        $service_title = $data['service_title'];
        $cust_name = $data['cust_name'];
        $cust_tel = $data['cust_tel'];
        $province_id = $data['province_id'];
        $city_id = $data['city_id'];
        $area_id = $data['area_id'];
        $address = $data['address'];
        $filename = dirname(dirname(__FILE__)).'/config/sys_city.php';
        $sys_city = file_get_contents($filename);
        $sys_city = json_decode($sys_city,1);
        $province_name = $city_name = $area_name = '';
        if (is_array($sys_city) && count($sys_city) > 0)foreach ($sys_city as $sys){
            if ($sys['id'] == $province_id){
                $province_name = $sys['name'];
                if (is_array($sys['son_val']) && count($sys['son_val']) > 0)foreach ($sys['son_val'] as $sys1){
                    if ($sys1['id'] == $city_id){
                        $city_name = $sys1['name'];
                        if (is_array($sys1['son_val']) && count($sys1['son_val']) > 0)foreach ($sys1['son_val'] as $sys2){
                            if ($sys2['id'] == $area_id){
                                $area_name = $sys2['name'];
                            }
                        }
                    }
                }
            }
        }
        $transaction = Yii::$app->db->beginTransaction();
        try {
            if (!$service_key || !$service_val || !$service_title) {
                throw new \Exception('请重新操作');
            }
            if (!$cust_tel) {
                throw new \Exception('请填写您的联系方式');
            }
            if (!$cust_name) {
                throw new \Exception('请填写您的姓名');
            }
            if (!$cust_tel) {
                throw new \Exception('请填写您的联系方式');
            }
            if (!$province_id) {
                throw new \Exception('请选择您的所在省');
            }
            if (!$city_id) {
                throw new \Exception('请选择您的所在市');
            }
            if (!$area_id) {
                throw new \Exception('请选择您的所在县/区');
            }
            if (!$address) {
                throw new \Exception('请选择您的详细地址');
            }
            $name = 'seq_CRM-'.$service_val;
            $time = date('Y-m-d H:i:s');
            $sys_seq = SysSeq::find()->where('name="'.$name.'"')->one();
            $sys_seq->edit_time = $time;
            $new_seq_no = tools::getSeqNo(intval($sys_seq->seq_no));
            $where = ['seq_no'=>intval($new_seq_no)];
            $ret = SysSeq::updateAll($where,'name=:name',[':name'=>$name]);
            if(!$ret){
                throw new \Exception('操作失败');
            }
            $service_vip = new ServiceVip();
            $service_vip->service_type = $service_key;
            $service_vip->service_code = $new_seq_no;
            $service_vip->cust_name = $cust_name;
            $service_vip->cust_tel = $cust_tel;
            $service_vip->province_id = $province_id;
            $service_vip->city_id = $city_id;
            $service_vip->area_id = $area_id;
            $service_vip->province_name = $province_name;
            $service_vip->city_name = $city_name;
            $service_vip->area_name = $area_name;
            $service_vip->address = $address;
            $service_vip->status = 1;
            $service_vip->creator = $service_vip->getCreator();
            $service_vip->create_time = $time;
            $service_vip->save();
            $service_vip_id = $service_vip->attributes['id'];
            if(!$service_vip_id){
                throw new \Exception('操作失败');
            }
            $transaction->commit();
            $this->retJson('操作成功',200);
        } catch (\Exception $e) {
            $transaction->rollBack();
            //add by allen.qiang 20180112 异常处理，日志优化 start
            error_log('error->' . __METHOD__ . ' error:' . $e->getMessage());
            //add by allen.qiang 20180112 异常处理，日志优化 end
            $this->retJson($e->getMessage(),500);
        }
    }
    
    public function actionSaveSysmemo(){
        $model = new ServiceVip();
        $data = Yii::$app->request->post();
        if ($data['service_vip_id']){
            $data_now['sys_memo'] = $data['sys_memo'];
            $data_now['editor'] = $model->getCreator();
            $data_now['edit_time'] = date('Y-m-d H:i:s',time());
            $where = ['id'=>$data['service_vip_id']];
            $ret = $model::updateAll($data_now,$where);
            if(!$ret){
                $this->retJson('操作失败',500);
            }
        }
        $this->retJson('操作成功',200);
    }
    
    public function actionExportServiceVip(){
        $key = Yii::$app->params['sys_redis_prefix'].'service_vip';
        $service_vip = Yii::$app->redis->get($key);
        $service_vip = json_decode($service_vip,1);
        if (count($service_vip) == 0){
            $this->retJson('未查到可导出数据，请刷新页面重试',500);
        }
        $service_vip_arr = [];
        foreach ($service_vip as $service_vip_val){
            $service_vip_arr[] = [
                'create_time'=>$service_vip_val['create_time'],
                'service_type_name'=>$service_vip_val['service_type_name'],
                'home_time'=>$service_vip_val['home_time'],
                'cust_name'=>$service_vip_val['cust_name'],
                'cust_tel'=>$service_vip_val['cust_tel'],
                'party_memo'=>$service_vip_val['party_memo'],
                'status'=>$service_vip_val['create_time'] == 1 ? '是' : '否',
            ];
        }
        $filed = ['create_time'=>'提交时间','service_type_name'=>'服务项目','home_time'=>'需求时间','cust_name'=>'姓名','cust_tel'=>'手机号','party_memo'=>'备注','status'=>'已处理'];
        $filename = 'service_vip_'.date('YmdHis').'.xls';
        $filename = iconv("utf-8", "gb2312", $filename);
        tools::exportExcel($filed, $service_vip_arr, $filename);

    }
}
